package com.wl.webfilter;

import com.sun.deploy.util.StringUtils;

import javax.net.ssl.StandardConstants;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 过滤器链
 * 若采用的是注解的方式进行配置，那么过滤器链的拦截顺序是按照全类名的先后顺序排序的
 * 若采用的是xml配置，那么按照配置的先后顺序执行
 */
@WebFilter(urlPatterns = {"*"}, initParams = {
        @WebInitParam(name = "encoding", value = "UTF-8")})
public class DemoFilter implements Filter {
    private String encoding = StandardCharsets.ISO_8859_1.toString();
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String encodingStr = filterConfig.getInitParameter("encoding");
        if (encodingStr != null && encodingStr != "") {
            encoding = encodingStr;
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        ((HttpServletRequest) request).setCharacterEncoding(encoding);
        System.out.println("拦截");
        // 放行
        chain.doFilter(request, response);
        System.out.println("放行");
    }

    @Override
    public void destroy() {
    }
}
